package cn.base.web.cahe.temporary;

import cn.base.web.cahe.TemporaryCache;
import cn.rengy.lang.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;

/**
 * 不引入redis时，临时缓存的解决方案
 */
@Component
@Slf4j
public class LocalTemporaryCache implements TemporaryCache  {
    private final SimpleCacheManager localTemporaryCache = new SimpleCacheManager();//不支持动态增加cache

    /**
     * 自定义CaffeineCache
     * @param caches
     */
    @Autowired
    public LocalTemporaryCache(List<CaffeineCache> caches){
        //原始Caffeine使用方式
        //Cache cache= Caffeine.newBuilder().maximumSize(1000).expireAfter(new SessionExpiry(Duration.ofMinutes(3))).build();
        //List<CaffeineCache> caches = new ArrayList<>();
        //caches.addAll(cacheList);
        localTemporaryCache.setCaches(caches);
        localTemporaryCache.initializeCaches();//必须调用初始化才能生效
    }
//    @PostConstruct
//    private void init(){
//
//    }
    @Override
    public void set(String key, Object value, Duration timeout) {
        Cache cache=getCacheByKey( key);
        String[] a =key.split(":");
        String kk=a[1];
        cache.put(kk,value);
    }

    @Override
    public Object get(String key) {
        Cache cache=getCacheByKey( key);
        String[] a =key.split(":");
        String kk=a[1];
        Cache.ValueWrapper valueWrapper=cache.get(kk);
        if (valueWrapper != null) {
            return valueWrapper.get();
        }
        return null;
    }

    @Override
    public Object getAndExpire(String key, Duration timeout) {
        return get(key);
    }

    @Override
    public void delete(String key) {
        String[] a =key.split(":");
        String kk=a[1];
        Cache cache=getCacheByKey(key);
        cache.evict(kk);
    }


    private Cache getCacheByKey(String key){
        String[] a =key.split(":");
        String cacheName=a[0];
        Cache cache=localTemporaryCache.getCache(cacheName);
        if(cache==null){

            throw new CustomException("必须初始化设置临时缓存对应的cacheName");
        }
        return cache;
    }
}
